package com.blogs.ui;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.blogs.component.BaseActivity;
import com.blogs.entity.IngComFeed;
import com.blogs.service.DeleteIngComment;
import com.blogs.service.GetIngComLine;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.FormatTime;
import com.blogs.tools.HtmlFormat;
import com.blogs.tools.ImageDownLoad;
import com.cnblogs.R;
import com.cnblogs.R.color;

public class IngDetail extends BaseActivity implements OnClickListener {
	private DBSharedPreferences sp;
	private Button title_include_back;
	private Button title_comment_write;
	private TextView title_include_title;
	private RelativeLayout title_top_bg;

	private ImageView ing_com_avatar;
	private TextView ing_com_author_tv;
	private TextView ing_com_time_tv;
	private TextView ing_com_con_tv;
	private LinearLayout ing_com_list_bg_ll;
	private LinearLayout ing_com_pro_bg;
	private ImageView ing_com_mask;
	private ScrollView ing_com_body;

	private int position;
	private String author;
	private String author_id;
	private String avatar;
	private String com_time;
	private String body;
	private String ingid;

	private ArrayList<IngComFeed> feedList;
	private IngComPublicReceiver ingComPublicReceiver;
	private Toast toast;
	private ProgressDialog proDdialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ing_detail);
		sp = new DBSharedPreferences(this);
		ViewGroup headview = (ViewGroup) findViewById(R.id.main_title_include);
		title_top_bg = (RelativeLayout) headview;
		title_include_title = (TextView) headview.findViewById(R.id.title_include_title);
		title_include_back = (Button) headview.findViewById(R.id.title_include_back);
		title_comment_write = (Button) headview.findViewById(R.id.title_comment_write);
		title_include_title.setText("闪存正文");
		title_include_back.setVisibility(View.VISIBLE);
		title_include_back.setOnClickListener(this);
		title_comment_write.setVisibility(View.VISIBLE);
		title_comment_write.setOnClickListener(this);

		ing_com_body = (ScrollView) findViewById(R.id.ing_com_body);
		ing_com_avatar = (ImageView) findViewById(R.id.ing_com_avatar);
		ing_com_author_tv = (TextView) findViewById(R.id.ing_com_author_tv);
		ing_com_time_tv = (TextView) findViewById(R.id.ing_com_time_tv);
		ing_com_con_tv = (TextView) findViewById(R.id.ing_com_con_tv);
		ing_com_list_bg_ll = (LinearLayout) findViewById(R.id.ing_com_list_bg_ll);
		ing_com_pro_bg = (LinearLayout) findViewById(R.id.ing_com_pro_bg);
		ing_com_mask = (ImageView) findViewById(R.id.ing_com_mask);

		ingComPublicReceiver = new IngComPublicReceiver();// 设置广播接收
		IntentFilter skinFilter = new IntentFilter();
		skinFilter.addAction("IngComPublicReceiver");
		registerReceiver(ingComPublicReceiver, skinFilter);

		this.InitSkin();
		this.InitProDailog();
		this.getIntentValue();
		this.setInitValue();
		this.requestCommentData();
	}

	private void InitSkin() {
		if (sp.GetIsDarkState()) {
			title_top_bg.getBackground().setLevel(2);
			ing_com_body.getBackground().setLevel(2);
			ing_com_mask.getBackground().setLevel(2);
			ing_com_con_tv.setTextColor(getResources().getColor(color.con_butom_night));
		} else {
			title_top_bg.getBackground().setLevel(1);
			ing_com_body.getBackground().setLevel(1);
			ing_com_mask.getBackground().setLevel(1);
			ing_com_con_tv.setTextColor(Color.parseColor("#000000"));
		}
	}

	private void InitProDailog() {
		proDdialog = new ProgressDialog(this);
		proDdialog.setIndeterminate(true);
		proDdialog.setCancelable(true);
		proDdialog.setMessage("正在删除闪存...");
	}

	private void getIntentValue() {
		this.position = getIntent().getIntExtra("position", 0);
		this.ingid = getIntent().getStringExtra("ingid");
		this.author = getIntent().getStringExtra("author");
		this.author_id = getIntent().getStringExtra("author_id");
		this.avatar = getIntent().getStringExtra("avatar");
		this.com_time = getIntent().getStringExtra("com_time");
		this.body = getIntent().getStringExtra("body");
	}

	private void setInitValue() {
		ing_com_author_tv.setText(this.author);
		if (sp.GetIsShowPic()) {
			ImageDownLoad.loadDrawable(this.avatar, ing_com_avatar);
		}
		ing_com_time_tv.setText(FormatTime.formatShort(this.com_time));
		ing_com_con_tv.setText(Html.fromHtml(this.body));
	}

	public void updateRequestData() {
		for (int i = 0; i < feedList.size(); i++) {
			this.addComView(feedList.get(i), false);
		}
		this.showLoading(false);
	}

	private void addComView(final IngComFeed feed, boolean isInsert) {
		View comView = View.inflate(this, R.layout.ing_com_item_layout, null);
		ComViewHolder comHolder = new ComViewHolder();
		comHolder.ing_com_item_avatar = (ImageView) comView.findViewById(R.id.ing_com_item_avatar);
		comHolder.ing_com_item_author = (TextView) comView.findViewById(R.id.ing_com_item_author);
		comHolder.ing_com_item_body = (TextView) comView.findViewById(R.id.ing_com_item_body);
		comHolder.ing_com_item_time = (TextView) comView.findViewById(R.id.ing_com_item_time);
		comHolder.ing_com_item_mask = (ImageView) comView.findViewById(R.id.ing_com_item_mask);

		if (sp.GetIsShowPic()) {
			comHolder.ing_com_item_avatar.setVisibility(View.VISIBLE);
			comHolder.ing_com_item_mask.setVisibility(View.VISIBLE);
			ImageDownLoad.loadDrawable(feed.author_avatar, comHolder.ing_com_item_avatar);
		} else {
			comHolder.ing_com_item_avatar.setVisibility(View.GONE);
			comHolder.ing_com_item_mask.setVisibility(View.GONE);
		}
		comHolder.ing_com_item_author.setText(Html.fromHtml(feed.author));
		comHolder.ing_com_item_body.setText(Html.fromHtml(HtmlFormat.FormatIngAt(feed.content)));
		comHolder.ing_com_item_time.setText(FormatTime.formatShort(feed.com_time));
		comView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent hintent = new Intent();
				hintent.setClass(IngDetail.this, IngPublicActivity.class);
				hintent.putExtra("position", position);
				hintent.putExtra("AtAuthor", feed.author);
				hintent.putExtra("ContentId", Integer.parseInt(ingid));
				hintent.putExtra("ReplyTo", Integer.parseInt(feed.author_id == null ? "0" : feed.author_id));
				hintent.putExtra("ParentCommentId", Integer.parseInt(feed.id));
				hintent.putExtra("FromMsg", feed.content);
				startActivity(hintent);
			}
		});
		final View fcomView = comView;
		comView.setOnLongClickListener(new OnLongClickListener() {

			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				String[] items = { "回复", "取消" };
				String[] items_d = { "回复", "删除", "取消" };
				final String[] f_items;
				if (!sp.GetNickName().equals("") && sp.GetNickName().equals(feed.author) && !feed.author_id.equals("0")) {
					f_items = items_d;
				} else {
					f_items = items;
				}

				new AlertDialog.Builder(IngDetail.this).setItems(f_items, new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (f_items[which].equals("回复")) {
							Intent hintent = new Intent();
							hintent.setClass(IngDetail.this, IngPublicActivity.class);
							hintent.putExtra("position", position);
							hintent.putExtra("AtAuthor", feed.author);
							hintent.putExtra("ContentId", Integer.parseInt(ingid));
							hintent.putExtra("ReplyTo", Integer.parseInt(feed.author_id == null ? "0" : feed.author_id));
							hintent.putExtra("ParentCommentId", Integer.parseInt(feed.id));
							hintent.putExtra("FromMsg", feed.content);
							startActivity(hintent);
						} else if (f_items[which].equals("删除")) {
							new AlertDialog.Builder(IngDetail.this).setTitle("删除闪存").setMessage("确定吗？")
									.setPositiveButton("是", new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int which) {
											proDdialog.show();
											new DeleteIngComment(sp.GetSessionID(), feed.id,
													new DeleteIngComment.IMsgCallBack() {

														public void onSuccess() {
															// TODO
															// Auto-generated
															// method stub
															showToast("删除评论成功");
															feedList.remove(feed);
															ing_com_list_bg_ll.removeView(fcomView);
															proDdialog.hide();
															Intent bintent = new Intent("IngComDelReceiver");
															bintent.putExtra("position", position);
															bintent.putExtra("author", feed.author);
															bintent.putExtra("com_time", feed.com_time);
															sendBroadcast(bintent);
														}

														public void onFailed(String err) {
															// TODO
															// Auto-generated
															// method stub
															showToast("删除评论失败," + err);
															proDdialog.hide();
														}
													}).Del();
										}
									}).setNegativeButton("否", null).show();
						} else {

						}
					}
				}).create().show();

				return false;
			}
		});
		if (sp.GetIsDarkState()) {
			comHolder.ing_com_item_body.setTextColor(getResources().getColor(color.con_butom_night));
			comHolder.ing_com_item_time.setTextColor(Color.parseColor("#c2c2c2"));
		} else {
			comHolder.ing_com_item_body.setTextColor(Color.parseColor("#000000"));
			comHolder.ing_com_item_time.setTextColor(Color.parseColor("#9A9A9A"));
		}
		if (isInsert) {
			ing_com_list_bg_ll.addView(comView, 0);
		} else {
			ing_com_list_bg_ll.addView(comView);
		}
	}

	private void requestCommentData() {
		this.showLoading(true);
		new GetIngComLine(sp.GetSessionID(), this.ingid, new GetIngComLine.IMsgCallBack() {

			public void onSuccess(ArrayList<IngComFeed> feeds) {
				// TODO Auto-generated method stub
				if (feedList == null)
					feedList = new ArrayList<IngComFeed>();
				feedList.clear();
				for (int i = 0; i < feeds.size(); i++) {
					feedList.add(feeds.get(i));
				}
				updateRequestData();
			}

			public void onFailed() {
				// TODO Auto-generated method stub
			}
		}).loadData();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == title_include_back) {
			finish();
		} else if (v == title_comment_write) {
			Intent hintent = new Intent();
			hintent.setClass(IngDetail.this, IngPublicActivity.class);
			hintent.putExtra("position", position);
			hintent.putExtra("ContentId", Integer.parseInt(this.ingid));
			hintent.putExtra("ReplyTo", Integer.parseInt(this.author_id));
			hintent.putExtra("AtAuthor", this.author);
			hintent.putExtra("FromMsg", this.body);
			hintent.putExtra("ParentCommentId", 0);
			startActivity(hintent);
		}
	}

	private void showLoading(boolean b) {
		if (b) {
			ing_com_pro_bg.setVisibility(View.VISIBLE);
		} else {
			ing_com_pro_bg.setVisibility(View.GONE);
		}
	}

	private void showToast(String text) {
		if (toast == null) {
			toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		} else {
			toast.setText(text);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(ingComPublicReceiver);
	}

	class IngComPublicReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			IngComFeed comfeed = new IngComFeed();
			comfeed.id = "0";
			comfeed.parent_id = intent.getIntExtra("ContentId", 0) + "";
			comfeed.author = intent.getStringExtra("author");
			comfeed.author_id = intent.getStringExtra("author_id") == null ? "0" : intent.getStringExtra("author_id");
			comfeed.content = intent.getStringExtra("Content");
			comfeed.com_time = intent.getStringExtra("comment_time");
			comfeed.author_avatar = intent.getStringExtra("avatar");
			addComView(comfeed, true);
			ing_com_body.scrollTo(0, 0);
		}
	}

	class ComViewHolder {
		ImageView ing_com_item_avatar;
		ImageView ing_com_item_mask;
		TextView ing_com_item_author;
		TextView ing_com_item_body;
		TextView ing_com_item_time;
	}
}
